// 导入 mysql 实例对象
const dbPool = require("../database/index");

const bcrypt = require("bcryptjs");
// bcrypt.hashSync("要加密的内容", 10); 加密
// bcrypt.compareSync("原始密码", "加密密码") 判断密码是否正确，返回布尔值

const jwt = require("jsonwebtoken");

const config = require("../config");


exports.register = function (req, res) {
  const sqlStr = "select * from user where username = ?";
  dbPool.query(sqlStr, req.body.username, (err, results) => {
    if (err) return res.cc(err);
    if (results.length === 1) return res.cc("用户名已被占用，修改用户名后重试！");
    // 加密密码
    req.body.password = bcrypt.hashSync(req.body.password, 10);
    const sqlStr = "insert into user set ?";
    dbPool.query(sqlStr, req.body, (err, results) => {
      if (err) return res.cc(err);
      if (results.affectedRows !== 1) return res.cc("用户注册失败！");
      res.cc("用户注册成功！", 1);
    })
  });
}

exports.login = function (req, res) {
  const sqlStr = "select * from user where username = ? and is_delete = 0";
  dbPool.query(sqlStr, req.body.username, (err, results) => {
    if (err) return res.cc(err);
    if (results.length === 0) return res.cc("用户不存在！");
    const isMatching = bcrypt.compareSync(req.body.password, results[0].password);
    if (!isMatching) return res.cc("密码不正确！");
    const user = { ...results[0], password: "", user_portrait: "", address: "" }
    console.log(user);
    const tokenStr = jwt.sign(user, config.jwtSecretKey, { expiresIn: "12h" });
    res.send({
      status: 1,
      message: "登录成功!",
      token: "Bearer " + tokenStr
    })
  })
}